<?php
    // 是不是灰度环境
    $isGrayEnv = in_array($_SERVER['SERVER_ADDR'], ["10.105.93.151", "10.143.43.138", "10.3.6.213"]);
    // 是不是生产环境 并且不是灰度环境
    $isProductionEnv = ($_SERVER['SERVER_NAME'] == 'w.weipaitang.com' || $_SERVER['SERVER_NAME'] == 'h5.weipaitang.org') && !$isGrayEnv;
    // 非生产环境使用 cdnt cdndev 域名
    $CDN_HOST = $_SERVER['SERVER_NAME'] == 'w.weipaitang.com' ? 'cdn.weipaitang.com' : 'cdn01t.weipaitang.com';

    // 不允许缓存
    header('Cache-Control: no-cache, no-store, must-revalidate');
    header('Pragma: no-cache');
    header('Expires: 0');

    $FILE_PATH = __FILE__;

    // 是不是开发人员
    $isDeveloper = in_array(get_property($commonArr['newUserInfo'], 'userinfoId', 0), [
        17196315, // 胡世豪
        7938673, // 王勇小号
        2, // 段文锟
    ]) || in_array(get_property($commonArr['newUserInfo'], 'telephone', 0), [
        // '13968038333', // 金老板
        '13173619622', // 林文豪
        '18668065162', // 王勇
        '15258880636', // 黄寿辉
        '15869001924', // 黄诚
        '15949565123', // 李俊
        '15868819694', // 周栗刚
        '15558066513', // 胡世豪
        '18958013866', // 章桐
        '13958002089', // 庄俊钰
        '13516852627', // 王伟敏
        '18969024990', // 叶月汶
        '15961885780', // 陈欢
        '15557151215', // 测试 姚慧
        '17682341470', // 测试 赵冷月
        '13306534323', // 任义祥
        '18368091254', // 臧屹凡
        '15658885300', // 徐老板
        '15258682933', // 陈欢
        '18701232109', // 王华怡
        '18612085856', // 徐娟娟
        '13306534323', // 任义祥
        '13216137786', // 张浩可
        '15158130302', // 王竟豪
        '13184247970', // 于楠
        '18668102905', // 俞奕臻
        '15345817033', // 华洁
        '18668117019', // 张乐阳
        '13184247970', // 邓超
        '13567154774', // 徐泽文
        '15869120517', // 王瑞江
        '13735477061', // 鲁大师
        '15101668168', // 赵锌泽
        '13372576167', // 王定方
        '18868810643', // 高瞻
        '15224035696', // 测试 刘果
        '18857458646', // 胡心杰
        '16729209555', // 鲁延涛
        '17326070627', // 鲁延涛-测试
        '15825521000', // 鲁延涛-测试
        '15397018556', // 测试 吴昱凝
        '18806539892', // 许将龙
        '15657512865', // 测试 郭玲玲
        '17857980913', // 测试 郭玲玲
        '13205815122', // 开发 农有宝
        '17098150035', // 开发 翟强
        '17682484682', // 赵逸风
        '15156183993', // 冯贺
        '17681844953', // 测试 张帆
        '18250198035', // 测试 康碧珍
        '17501622900', // 王佳慧
        '18668200286', // 张英杰
        '15257150019', // 姚佳辉
        '13185067122', // 祝海燕
        '13221081028', // 康胜利
        '18358185916', // 测试王倩倩
        '13822136046', // 测试王倩倩
        '17605027100', // 测试林素玲
        '16608969705', // 测试 常海洋
        '15111111111', // 测试
        '15088618910', // 开发 董承
        '16603921011', // 测试 常晓妮
        '15868129380', // 开发 郭远长
        '18957137445', // 开发 阳文浩
        '15558175993', // 开发 冯贺
        '13564198408', // 刘勇强
        '15258387247', // 石玲燕
    ]);

    if(
        !$isProductionEnv // 不是生产环境
        || get_property($_GET, 'fr', '') == 'wpt_front_debug1' // search fr=wpt_front_debug1，方便用户进入灰度环境
    ){
        $isDeveloper = true;
    }

    $fileName = '';

    // 使用灰度测试版本
    if (
        $isProductionEnv // 生产环境
        && $isDeveloper // 开发人员
        && get_property($_COOKIE, 'wpt_front_debug1', 'false') == 'true' // cookie wpt_front_debug1 != 'false' 方便开发人员切换到正式环境
    ) {
        $fileName = 'router-gray.php';
    } else {
        $fileName = 'router.php';
    }

    // 在dev环境，根据不同的前端分支，加载不同的router文件，默认加载develop
    if ($_SERVER['SERVER_NAME'] == 'dev.weipaitang.com') {
        $CDN_HOST = $_SERVER['SERVER_NAME'];
    }

    $basedir = dirname(__FILE__);

    // cookie中添加h5版本号 relase/webApp/2019xxx-xxx
    $basedirArr = explode("/webApp/", $basedir);
    // 有些测试环境的路径不包含/webApp/，所以做个空判断
    $h5Verison = isset($basedirArr[1]) ? $basedirArr[1] : "defaultVerison";
    setcookie("h5V", $h5Verison, time()+60*60*24*365, "/", ".weipaitang.com");

    if ($isProductionEnv && $isDeveloper) {
        $basedir = '/webApp';
    }
    $routerPath = $basedir . '/' . $fileName;
    include "$routerPath" ;

    // 获取子账号可访问配置
    $scopeUserAllowUrls = config_item('scope_user_allow');
    // 静态资源host，主要用来修复灰度环境获取线上静态资源的问题
    $STATIC_HOST = $isProductionEnv ? $CDN_HOST : $_SERVER['SERVER_NAME'];

    // 是否使用CrossOrigin加载js资源，以捕获详细的错误日志
    $useCrossOrigin = false;
    if ($isProductionEnv) {
        // 线上环境，使用crossOrigin加载cdn.weipaitang.com下的静态资源
        $useCrossOrigin = true;
    }

    // 获取用户id尾号用来灰度测试，默认为-1
    $userinfoSlot = -1;
    $userinfoSlot2 = -1;
    $userinfoSlot3 = -1;
    $userinfoId = '';

    if (!empty($commonArr['newUserInfo'])) {
        $userinfoId = get_property($_GET, 'userinfoId', get_property($commonArr['newUserInfo'], 'userinfoId', 0));
        // id小于100的不在测试范围内，这些主要是老板、测试的账号
        $isInTestWhite = in_array(get_property($commonArr['newUserInfo'], 'telephone', 0), [
            '13968038333', // 金老板
            '15658885300', // 徐老板
            '13073622535',
            '15088692749',
        ]);

        // 生产环境且在白名单内
        if ($isProductionEnv && $isInTestWhite) {
            $userinfoSlot = 10;
        } else if (!$isProductionEnv || $userinfoId > 100) {
            $userinfoSlot = substr($userinfoId, -1);
            $userinfoSlot2 = substr($userinfoId, -2);
            $userinfoSlot3 = substr($userinfoId, -3);
        }
    }
?>
<!DOCTYPE html>
<html lang="zh">
    <head>
        <meta charset="UTF-8">
        <meta name="apple-mobile-web-app-title" content="微拍堂">
        <meta name="format-detection" content="telephone=no">
        <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
        <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
        <meta http-equiv="Pragma" content="no-cache">
        <meta http-equiv="Expires" content="0">
        <link rel="dns-prefetch" href="//cdn.weipaitang.com">
        <link rel="manifest" href="//cdn.weipaitang.com<?= $router['sw-manifest']['path'] ?>">
        <meta name="renderer" content="webkit">
        <meta name="force-rendering" content="webkit">
        <meta name="theme-color" content="#000000">
        <title>微拍堂</title>
        <style type="text/css">
            style, title {
                display: none;
            }
            body {
                margin: 0 auto;
            }
            .page-placeholder {
                min-height: 100vh;
                margin: 0 auto;
                background-position: center 40%;
                background-repeat: no-repeat;
                background-size: 33.33% auto;
                background-image: url("");
            }
            .default-background {
                background-color: #f4f6f6;
            }
        </style>
    </head>
    <body>
    <script>
        (function() {
            var ua = navigator.userAgent;
            if (!ua.match(/(iPhone|iPad|iPod)/)) return;
            var matched = ua.match(/OS ([\d_\.]+) like Mac OS X/);
            if (!matched[1]) return;
            // Match all iOS 12, because we don't know the time when Apple fixed the bug.
            if (matched[1].indexOf('12') !== 0) return;
            Array.prototype._reverse = Array.prototype.reverse;
            Array.prototype.reverse = function reverse() {
                this.length = this.length;
                return Array.prototype._reverse.call(this);
            }
            var nonenum = {enumerable: false};
            Object.defineProperties(Array.prototype, {
                _reverse: nonenum,
                reverse: nonenum,
            });
        })();
        ;(function () {
            var UA = window.navigator.userAgent;
            var os = {
                ios: UA.match(/iphone|ipad|ipod/i),
                ipad: UA.match(/ipad/i),
                iphone: UA.match(/iphone/i),
                android: UA.match(/android/i),
                webkit: UA.match(/webkit/i),
                ie: UA.match(/MSIE/i),
                wechat: UA.match(/micromessenger/i),
                wpt: UA.match(/wptmessenger/i),
                xcx: window.__wxjs_environment === 'miniprogram',
                bdXcx: UA.match(/swan\//i),
            };
            os.phone = os.ios || os.android;
            os.pc = !os.phone;
            os.wptfullscreen = !!UA.match(/wptfullscreen\/true/i);

            window.__wpt_os = os;

            document.querySelector('html').className += ' ' + Object.keys(os).map(function (key) {
                return os[key] && 'device-' + key;
            }).filter(function (i) {
                return i;
            }).join(' ') + (os.wptfullscreen ? '' : ' default-background');
        })();
    </script>
    <style type="text/css">
        .page-placeholder {
            width: 7.5rem;
        }
    </style>

    <div id="message-alert"></div>
    <div id="J_Page" class="page-placeholder">
        <div id="Page" class='curPage' data-page="1"></div>
    </div>

    <script>
        (function() {
            if (Object.getOwnPropertySymbols) {
                // 修复安卓5.1 Object.getOwnPropertySymbols报错问题
                try {
                    Object.getOwnPropertySymbols(1);
                } catch (err) {
                    var getOwnPropertySymbols = Object.getOwnPropertySymbols;
                    Object.getOwnPropertySymbols = function (any) {
                        try {
                            return getOwnPropertySymbols.call(Object, any);
                        } catch (err) {
                            return [];
                        }
                    }
                }
            }
        })();
    </script>
    <script src="//<?= $STATIC_HOST ?>/webApp/app/zepto.min.js?v=1"></script>
    <script src="//<?= $STATIC_HOST ?>/webApp/app/babel-polyfill-7.min.js?v=1"></script>
    <script src="//<?= $STATIC_HOST ?>/webApp/app/modernizr.js?v=1"></script>
    <script src="//<?= $STATIC_HOST ?>/webApp/app/wpt-reporter.js?v=6" crossorigin="anonymous"></script>
    <script>
        // 防止Zepto被重写
        ;(function(){
            Object.defineProperty(window, 'Zepto', {value: Zepto, writable: false});
            Object.defineProperty(window, '$', {value: Zepto, writable: false});
        })();
        (function() {
            var isDeveloper = <?= $isDeveloper ? "true" : "false" ?>;
            var isProductionEnv = <?= $isProductionEnv ? "true" : "false" ?>;
            var isGrayEnv = <?= $isGrayEnv ? "true" : "false" ?>;

            var reporter = new WPTReporter({
                project: 'webApp',
                error: {
                    alert: isDeveloper,
                    log: isDeveloper,
                },
                onBeforeSend: function(data) {
                    // 生产及灰度环境上均报错误
                    if ((!isProductionEnv && !isGrayEnv) || window.WPT_LOCAL_DEV) {
                        console.error('【注意】非生产环境error:', data)
                        return false;
                    }
                    data.version = '<?= $FILE_PATH ?>';
                    if (isDeveloper) {
                        data.isDeveloper = isDeveloper;
                    }
                    if (window.WPT) {
                        data.ip = WPT.ip;
                        data.userinfoUri = WPT.userinfo.userinfoUri;
                        data.username = WPT.userinfo.nickname;
                        data.serverTime = WPT.nowTime;
                        data.referrer = WPT.referrer || '';
                    }
                    if (data.JSRuntimeError && window.WPTCheckIsImpError && window.WPTCheckIsImpError(data)) {
                        data.impError = 1;
                    }
                    if (isGrayEnv) {
                        data.env = '【灰度环境错误】';
                    }
                    data.documentReferrer = document.referrer || '';
                    return data;
                },
            })
            window.reportError = function(data) {
                reporter.report(data);
            }
        })();
        (function() {
            // 为app js bridge加载太慢做一个兼容
            window.triggerAppEvent = window.triggerAppEvent || function(eventName, params) {
                $(document).trigger('app-event-' + eventName, params);
            };
        })();
    </script>
    <script type="text/javascript">
        !function() {
            var $html = document.querySelector('html');
            function setRem() {
                var clientWidth = $html.clientWidth || window.screen.width;
                if (window.__wpt_os.pc) {
                    clientWidth = Math.min(clientWidth, 640);
                }
                $html.style.fontSize = clientWidth / 7.5 + "px";
                var div = document.createElement("div");
                div.style.width = "7.5rem";
                document.body.appendChild(div);
                $html.style.fontSize = $html.style.fontSize.replace("px", "") * clientWidth / div.clientWidth + "px";
                document.body.removeChild(div);
            }
            var b = null;
            window.addEventListener("resize", function() {
                if(window.__wpt_os.wpt && window.__wpt_os.android){
                    setRem()
                }else{
                    clearTimeout(b);
                    b = setTimeout(setRem, 300);
                }
            }, !1);
            setRem();
        }(window);
        // 后端直出信息，挂在这里
        window.WPT = window.WPT || {};
        WPT.appId = '<?= APP_ID ?>';
        WPT.WEI_HOST = location.origin + "/";
        WPT.recordPageLimit = $.os.android ? 3 : 5;
        WPT.allPage = {};
        WPT.os = {};

        // 新增新的用户信息
        WPT.userinfo = {
            userinfoSid: '<?= empty($userinfoId) ? '' : wptEncrypt($userinfoId) ?>',
            userinfoUri: '<?= get_property($commonArr['newUserInfo'], 'userinfoUri', 0) ?>',
            isNewUser: <?= get_property($commonArr['newUserInfo'], 'isNewUser', 0) ?>,
            isChildLogin: <?= get_property($commonArr['newUserInfo'], 'isChildLogin', 0) ?>,
            isSubscribe: <?= get_property($commonArr['newUserInfo'], 'isSubscribe', 0) ?>,
            nickname: '<?= get_property($commonArr['newUserInfo'], 'nickname', 0) ?>',
            headimgurl: '<?= get_property($commonArr['newUserInfo'], 'headimgurl', 0) ?>',
            memberLevel: <?= get_property($commonArr['newUserInfo'], 'memberLevel', 0) ?>,
            memberTime: <?= get_property($commonArr['newUserInfo'], 'memberTime', 0) ?>,
            expiredTime: <?= get_property($commonArr['newUserInfo'], 'expiredTime', 0) ?>,
            hasTelephone: <?= empty(get_property($commonArr['newUserInfo'], 'telephone', 0)) ? 0 : 1 ?>,
            userinfoSlot: '<?= $userinfoSlot ?>',
            userinfoSlot2: '<?= $userinfoSlot2 ?>',
            userinfoSlot3: '<?= $userinfoSlot3 ?>',
        };

        WPT.userinfo.buyerLevel = WPT.userinfo.memberLevel + 1;

        WPT.scopeUserAllowUrls = <?= json_encode($scopeUserAllowUrls) ?>;
        WPT.API_HOST = '//api.weipaitang.com/';
        WPT.SCANLOGINHOST = "<?= SCANLOGINHOST ?>";
        WPT.ip = '<?= getIp() ?>';
        WPT.serverIp = '<?= empty($_SERVER['SERVER_ADDR']) ? '' : $_SERVER['SERVER_ADDR'] ?>';
        WPT.router = <?= json_encode($router) ?>;
        WPT.CDNURL = "//<?= $CDN_HOST; ?>/";
        WPT.JSCDNURL = "//<?= $CDN_HOST; ?>";
        WPT.isGray = <?= $isGrayEnv ? "true" : "false" ?>;
        WPT.debug = <?php echo $isProductionEnv ? "false" : "true"; ?>;
        WPT.signConfig = <?= json_encode($commonArr['signPackage']) ?>;
        if (window.__wpt_os.wechat) {
            WPT.device = 'wechat';
        } else if (window.__wpt_os.wpt) {
            WPT.device = 'app';
        } else {
            WPT.device = 'web';
        }
        WPT.isDeveloper = <?= $isDeveloper ? "true" : "false" ?>;
        WPT.loadScriptHost = (location.host == 'w.weipaitang.com' && !WPT.isGray) ? WPT.JSCDNURL : ''; // 生产环境走cdn
        WPT.nowTime = <?= time() ?>;
        WPT.serverLoginTime = WPT.nowTime;
        WPT.getNowTime = (function() {
            var time = Date.now();
            return function() {
                var timeSpace = Math.round((Date.now() - time) / 1000);
                return WPT.serverLoginTime + timeSpace;
            }
        })();
        WPT.loadScriptUseCrossorigin = <?= $useCrossOrigin ? "true" : "false" ?> || location.href.indexOf('fr=loadScriptUseCrossorigin') > 0; // 是否使用crossorigin
        WPT.setRefer = function(){};
        window.bridgeConnect = function(){};
        $(document).on('wptLoadJs:success', function() {
            window.wptLoadJsSuccess = true;
        });

        <?php if ( $isProductionEnv ): ?>
            var forceReloadTime = Number(sessionStorage.getItem('forceReload')) || 0;

            if ((Date.now() / 1000 - WPT.serverLoginTime > 60 * 60) && forceReloadTime < 2) {
                sessionStorage.setItem('forceReload', forceReloadTime + 1);

                var url = window.location.href;
                if (url.indexOf('?') > -1) {
                    url += '&uniq=' + Date.now();
                } else {
                    url += '?uniq=' + Date.now();
                }

                window.location.href = url;
            }
        <?php endif; ?>
    </script>
    <script>
        if (WPT.device == 'wechat') {
            document.write('<script src="' + WPT.loadScriptHost + '/webApp/app/jweixin-1.6.0.js"><\/script>');
        }
        if (/miniProgram_dy/i.test(window.location.search) || /ToutiaoMicroApp/i.test(window.navigator.userAgent)) {
            document.write('<script src="https://s3.pstatp.com/toutiao/tmajssdk/jssdk-1.0.0.js"><\/script>');
        }
        if (location.href.indexOf('fr=bdxcx') > 0 || /swan\//i.test(window.navigator.userAgent)) {
            document.write('<script src="https://b.bdstatic.com/searchbox/icms/searchbox/js/swan-2.0.21.js"><\/script>');
        }
    </script>
    <?php
        // 开发人员，加载代理工具
        if ( $isDeveloper ): ?>
        <script>
            var loadScriptHost = WPT.loadScriptHost;
            if (location.search.indexOf('proxyDebug') > -1) {
                loadScriptHost = 'https://localhost:8001';
            }
            document.write('<script src="' + loadScriptHost + '/webApp/app/proxy.js?v=1.35"><\/script>');
        </script>
    <?php endif; ?>
    <script type="text/javascript">
        function isCachesAvaliable() {
            var isDebugPCUser = (WPT.isDeveloper && ('caches' in window));
            return isDebugPCUser;
        }

        if (localStorage.getItem("WPT.wechat") == 1) {
            WPT.os.device = 'wechat';
        }
        function loadMainJS() {
            function loadScript(src) {
                if (WPT.loadScriptUseCrossorigin) {
                    document.write('<script src="' + src + '" crossorigin="anonymous"><\/script>');
                } else {
                    document.write('<script src="' + src + '"><\/script>');
                }
            }

            // 加载 manifest
            loadScript(WPT.loadScriptHost + WPT.router.manifest.path)
            // 加载 vendor
            loadScript(WPT.loadScriptHost + WPT.router.vendor.path)
            // 加载main
            loadScript(WPT.loadScriptHost + WPT.router.main.path)
        }

        loadMainJS();
    </script>
    </body>
</html>
